﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace AspDotNet.Framework.CommonLibs
{
    public class SysEnvironmentVariableHelper
    {
        [DllImport("Kernel32.DLL", SetLastError = true)]
        static extern bool SetEnvironmentVariable(string lpName, string lpValue);

        public static void SetSysEnvironmentByName(string name, string value)
        {
            var originalValue = GetSysEnvironmentByName(name);
            if (originalValue == null || string.Equals(originalValue, value))
                return;
            SetEnvironmentVariable(name, value);
        }

        /// <summary>
        /// 获取系统环境变量
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetSysEnvironmentByName(string name)
        {
            return OpenSysEnvironment().GetValue(name)?.ToString();
        }

        /// <summary>
        /// 设置系统环境变量(需要用管理员权限)
        /// </summary>
        /// <param name="name">变量名</param>
        /// <param name="strValue">值</param>
        public static void SetSysEnvironment(string name, string strValue)
        {
            OpenSysEnvironment().SetValue(name, strValue ?? string.Empty);
        }

        /// <summary>
        /// 打开系统环境变量注册表
        /// </summary>
        /// <returns>RegistryKey</returns>
        private static RegistryKey OpenSysEnvironment()
        {
            RegistryKey regLocalMachine = Registry.LocalMachine;
            RegistryKey regSYSTEM = regLocalMachine.OpenSubKey("SYSTEM", true);//打开HKEY_LOCAL_MACHINE下的SYSTEM 
            RegistryKey regControlSet001 = regSYSTEM.OpenSubKey("ControlSet001", true);//打开ControlSet001 
            RegistryKey regControl = regControlSet001.OpenSubKey("Control", true);//打开Control 
            RegistryKey regManager = regControl.OpenSubKey("Session Manager", true);//打开Control 

            RegistryKey regEnvironment = regManager.OpenSubKey("Environment", true);
            return regEnvironment;
        }
    }
}
